import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import { getEmptyOptions } from '@/dictionary';
import ChartForm from '@/pages/Statistics/WorkVal/components/ChartForm';
import Styles from '@/pages/Statistics/WorkVal/components/Common.less';
import { statisticWorkStatusControllerGetMonthYearWorkStatus } from '@/services/ess/statisticWorkstatus';
import { useIntl } from '@umijs/max';
import { Spin } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { SubmitType } from './Type';

const MonthChart: React.FC = () => {
  const intl = useIntl();
  const [chartLoading, setChartLoading] = useState(false);
  const [option, setOptions] = useState<MyChartOption>();
  const chartRef = useRef(null);
  const getSeriesData = (key: string, options: API.WorkStatusPage[]) => {
    return options.map((i: API.WorkStatusPage) => {
      return i[key];
    });
  };
  const handleSubmit = (value: SubmitType) => {
    if (option) {
      setChartLoading(true);
    }
    const params = {
      dateType: 'month',
      date: dayjs(value.date).format('YYYY-MM'),
      dataType: value.areaIdList ? '3' : value.staticDimension === 'station' ? '1' : '2',
      code: value.areaIdList ? '' : value.code,
      areaIdList: value.areaIdList,
    };
    statisticWorkStatusControllerGetMonthYearWorkStatus(params)
      .then((res) => {
        if (res.success && res.data && res.data.length > 0) {
          const xAxis = res.data.map((i: API.WorkStatusPage) => {
            return i.date;
          });
          let seriesData = [
            {
              stack: 'time',
              name: intl.formatMessage({ id: 'statistics.work.chargeTime' }),
              type: 'bar',
              yAxisIndex: 0,
              data: getSeriesData('chargeTime', res.data),
              itemStyle: {
                color: '#56D433',
              },
            },
            {
              stack: 'time',
              name: intl.formatMessage({ id: 'statistics.work.dischargeTime' }),
              type: 'bar',
              yAxisIndex: 0,
              data: getSeriesData('dischargeTime', res.data),
              itemStyle: {
                color: '#1A6CFE',
              },
            },
            {
              stack: 'time',
              name: intl.formatMessage({ id: 'statistics.work.standbyTime' }),
              type: 'bar',
              yAxisIndex: 0,
              data: getSeriesData('standbyTime', res.data),
              itemStyle: {
                color: '#FFD50C',
              },
            },
            {
              stack: 'time',
              name: intl.formatMessage({ id: 'statistics.work.debugTime' }),
              type: 'bar',
              yAxisIndex: 0,
              data: getSeriesData('debugTime', res.data),
              itemStyle: {
                color: '#8662F1',
              },
            },
            {
              stack: 'time',
              name: intl.formatMessage({ id: 'statistics.work.faultTime' }),
              type: 'bar',
              yAxisIndex: 0,
              data: getSeriesData('faultTime', res.data),
              itemStyle: {
                color: '#FF5353',
              },
            },
            {
              stack: 'total',
              name: intl.formatMessage({ id: 'statistics.work.chargeTimes' }),
              type: 'bar',
              yAxisIndex: 1,
              data: getSeriesData('chargeCount', res.data),
              itemStyle: {
                color: '#BBF068',
              },
            },
            {
              stack: 'total',
              name: intl.formatMessage({ id: 'statistics.work.dischargeTimes' }),
              type: 'bar',
              yAxisIndex: 1,
              data: getSeriesData('dischargeCount', res.data),
              itemStyle: {
                color: '#508FFF',
              },
            },
            {
              stack: 'total',
              name: intl.formatMessage({ id: 'statistics.work.standbyTimes' }),
              type: 'bar',
              yAxisIndex: 1,
              data: getSeriesData('standbyCount', res.data),
              itemStyle: {
                color: '#FFFF00',
              },
            },
            {
              stack: 'total',
              name: intl.formatMessage({ id: 'statistics.work.debugTimes' }),
              type: 'bar',
              yAxisIndex: 1,
              data: getSeriesData('debugCount', res.data),
              itemStyle: {
                color: '#CAB8FF',
              },
            },
            {
              stack: 'total',
              name: intl.formatMessage({ id: 'statistics.work.faultTimes' }),
              type: 'bar',
              yAxisIndex: 1,
              data: getSeriesData('faultCount', res.data),
              itemStyle: {
                color: '#FF9494',
              },
            },
          ];
          if (value.staticDimension !== 'station') {
            seriesData = seriesData.filter(
              (item) => item.name !== intl.formatMessage({ id: 'statistics.work.debugTimes' }),
            );
            seriesData = seriesData.filter(
              (item) => item.name !== intl.formatMessage({ id: 'statistics.work.debugTime' }),
            );
          }
          const chartOptions: MyChartOption = {
            tooltip: {
              trigger: 'axis',
            },
            xAxis: {
              type: 'category',
              data: xAxis,
              axisLabel: {
                formatter: (value: string, index: number) => {
                  return index + 1;
                },
              },
              axisTick: {
                alignWithLabel: true,
              },
            },
            grid: {
              top: 100,
              left: 50,
              right: 50,
            },
            legend: {
              top: 0,
              right: 50,
              icon: 'rect',
              orient: 'horizontal', // 水平排布
              itemWidth: 20, // 各图例项宽度
              itemHeight: 10, // 各图例项高度
              width: value.staticDimension === 'station' ? 420 : 380, // 图例总宽度，此处需计算以适配5个图例项
            },
            yAxis: [
              {
                type: 'value',
                name: intl.formatMessage({ id: 'statistics.common.unitMins' }),
                axisLine: {
                  show: true,
                },
              },
              {
                type: 'value',
                name: intl.formatMessage({ id: 'statistics.common.unitTimes' }),
                axisLine: {
                  show: true,
                },
              },
            ],
            series: seriesData,
          };
          chartRef?.current?.instance().clear();
          setOptions(chartOptions);
          setChartLoading(false);
        } else {
          if (
            chartRef?.current?.instance() &&
            chartRef?.current?.instance().getOption()?.series.length !== 0
          ) {
            chartRef?.current?.instance().clear();
          }
          setOptions(getEmptyOptions());
          setChartLoading(false);
        }
      })
      .catch(() => {
        setChartLoading(false);
      });
  };
  useEffect(() => {
    setChartLoading(true);
  }, []);
  return (
    <div className={Styles.chartContent}>
      <ChartForm dateType={'month'} submitForm={handleSubmit} />
      <Spin spinning={chartLoading}>
        <EchartsComponent
          ref={chartRef}
          option={option}
          width={'auto'}
          height={500}
        ></EchartsComponent>
      </Spin>
    </div>
  );
};

export default MonthChart;
